package com.ai.aimanageapi.service;

import com.ai.aimanageapi.entity.User;
import com.ai.aimanageapi.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    // 添加用户
    public User addUser(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return userRepository.save(user);
    }

    // 获取所有用户
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    // 根据 ID 获取用户
    public Optional<User> getUserById(Long id) {
        return userRepository.findById(id);
    }

    // 更新用户
    public User updateUser(Long id, User userDetails) {
        if ("admin".equals(userRepository.findById(id).map(User::getUsername).orElse(null))) {
            return null; // 禁止修改 admin 用户
        }
        Optional<User> optionalUser = userRepository.findById(id);
        if (optionalUser.isPresent()) {
            User user = optionalUser.get();
            user.setUsername(userDetails.getUsername());
            return userRepository.save(user);
        }
        return null;
    }

    // 删除用户
    public void deleteUser(Long id) {
        if (!"admin".equals(userRepository.findById(id).map(User::getUsername).orElse(null))) {
            userRepository.deleteById(id);
        }
    }

    // 重置密码
    public void resetPassword(Long id, String newPassword) {
        Optional<User> optionalUser = userRepository.findById(id);
        if (optionalUser.isPresent()) {
            User user = optionalUser.get();
            user.setPassword(passwordEncoder.encode(newPassword));
            userRepository.save(user);
        }
    }
}